<?php
/**
 * Created by PhpStorm.
 * User: songs
 * Date: 2019/8/23
 * Time: 10:07
 */

namespace App\admin\TableView\BaseClass;

use App\admin\Service\OA;
use App\Jobs\Fun;
use App\Jobs\Yii\Html;
use App\Jobs\Yii\Yii;
use App\Utilities\Upload;

abstract class BaseViewList
{

    const ButtonDiv = 'ButtonDiv';
    const Button_checkbox = 'Button_checkbox';
    const Button_control = 'control';
    const Button_Edit = 'edit';
    const Button_Delete = 'delete';

    const Api_TableStruct = 'Api_TableStruct';
    /**
     * 视图版
     */
    const Api_TableStructView = 'Api_TableStructView';
    const Api_TableContent = 'Api_TableContent';
    const Api_MainView = 'Api_MainView';
    const Api_Edit = 'Api_Edit';
    const Api_Delete = 'Api_Delete';
    const Api_DeleteArray = 'Api_DeleteArray';
    const Api_Form = 'Api_Form';

    const dialog_Img = 'img';
    const dialog_number = 'INTtext';
    const dialog_time = 'time';
    const dialog_text = 'text';
    const dialog_email = 'email';
    const dialog_phone = 'phone';
    const dialog_checkbox = 'checkbox';
    const dialog_list='list';

    const dialog_texthtml='texthtml';
    const dialog_textarea = 'textarea';

    public $Request=null;///Request $request
    ///
    public function __construct($Request=null)
    {
        $this->Request=$Request;
    }

    /**
     * Returns the fully qualified name of this class.
     * @return string the fully qualified name of this class.
     * @deprecated since 2.0.14. On PHP >=5.5, use `::class` instead.
     */
    public static function className()
    {
        return get_called_class();
    }
    public $html='';

    const TAG_ERROR = '1';
    const TAG_OK = '0';

    public $topTitle='标题';

    public $breadcrumb='<li><a href="/admin">Home</a></li>
        <li><a href="javascript:;">系统</a></li>
        <li class="active">用户列表</li>';

    /**
     * 记录当前显示方式,true为显示在浏览器,false显示在excel表格中
     */
    public $showEcho = true;

    /**
     * 输出方式,如果为true为保存,否则为下载
     */
    public $echo_Save = true;

    /**
     * 返回所使用的model
     */
    abstract public function get_model();

    /**
     * 表格的id
     */
    //  public $id='BaseViewList';

    /**
     * 获取表格的唯一名字
     */
    public function getName() {
        return md5(self::className());
    }

    public $show_add = true; ///显示添加按钮
    /**
     * 是否显示删除按钮
     */
    public $show_delete = true;

    /**
     * 是否显示复选框
     */
    public $show_select_box = true;

    /**
     * 自动检查是否有新数据,如果为0,则表示不自动检查,单位是秒
     */
    public $auto_detection = 30;
    public $count = 0; ///当前条件搜索的行数
    public $PageSize =20;
    private $pages; ///分页对象

    /**
     * 需要继承,然后定义每行需要显示的数据格式
     */
    abstract public function Labels(); /* {
      return array(
      /*
      return array(
      'img'=>'',
      'title'=>'',
      'add_time'=>'',
      'description'=>array('style'=>'width:250px'),
      ,
      'control'=>[
      'edit',
      'delete'
      ]
      );
      );
      }
     */

    /**
     * 对话框中的各个字段
     */
    public function dialog() {
        return []; /*
          return array(
          array(
          'title'=>'分类',
          'zd'=>'cate_id',
          ///'type'=>'img'
          ),
          array(
          'title'=>'颜色',
          'zd'=>'color_id'
          ),
          array(
          'title'=>'是否宽屏',
          'zd'=>'widescreen',
          'type'=>'list',
          'data'=>array(
          \app\models\Bizhi::B_kuanping=>'宽屏',
          \app\models\Bizhi::B_changgui=>'常规'
          )
          ),

          array(
          'title'=>'图片',
          'zd'=>'file',
          'type'=>'img'
          ),
          ); */
    }

    /**
     * 显示顶部的信息,比如控制按钮
     */
    public function html_Top() {
        $html = $this->html_top_tongji();
        $html.=$this->html_top_kongzhi();
        return $html;
    }

    /**
     * 其它控制按钮
     */
    public function html_top_qita() {
        return '';
    }

    /**
     * 显示一个顶部的控制按钮
     */
    public function html_top_kongzhi() {
        $html = $this->html_top_qita() . $this->html_kongzhi_delete();
        $html.=$this->html_kongzhi_add();
        if ($this->BarChart) {
            $html.="<a href='?barmode=true' target= '_blank' class='btn  achartico' title='使用图形模式查看'><i class='chartico'></i></a>";
        }
        return '<div class="kz">' . $html . '</div>';
    }

    /**
     * 顶部的删除按钮,$id为空时,仅删除选择的内容,$title为删除时显示的标题
     */
    public function html_kongzhi_delete($id = '', $title = '') {

        if (!$this->show_delete) {
            return '';
        }

        if ($id === '') {
            $id = 'select';
        }
        return Html::button(
            '删除', [
            'list_id' => $id,
            'list_title' => $title,
            'class' => 'delete'
        ], Html::Colordanger
        );
    }

    /**
     * 控制的添加按钮
     */
    public function html_kongzhi_add() {
        if (!$this->show_add) {
            return '';
        }
        return Html::button('添加', [
            'onclick' => 'bvl.on_edit()'
        ], Html::Colorinfo
        );
    }

    /**
     * 控制的编辑按钮
     */
    public function html_kongzhi_edit($id) {
        return Html::button('编辑', ['list_id' => $id]);
    }

    /**
     * 简单显示一个统计信息
     */
    public function html_top_tongji() {
        $p = '<p class="top_tongji">查询到的数据有' . $this->count . '行</p>';


        ///'自动刷新';
        return $p ;
    }

    /**
     * 显示每行顶部标题的数据
     */
    public function html_Labels($key) {
        ///var_dump(method_exists($this,'Label_'.$key));exit;
        $fun = 'Label_' . $key;
        if (method_exists($this, $fun)) {
            return $this->$fun($key);
        } else {
            return $this->Label_default($key);
        }
    }

    /**
     * 显示一个全选按钮
     */
    public function echo_th_select() {
        if (!$this->show_select_box) {
            return '';
        }

        return '<th td_class="td_select" title="全选" class="tab_select">' . Html::checkbox('all') . '</th>';
    }

    /**
     * 显示每行数据的选择按钮
     */
    public function echo_td_select($model) {
        if (!$this->show_select_box) {
            return '';
        }
        return '<td class="td_select"  bvl_id="' . $this->model_to_id($model) . '">' . Html::checkbox('all', false, ['bvl_id' => $this->model_to_id($model)]) . '</td>';
    }

    /**
     * 显示一行数据
     */
    public function echo_tbody_tr($model) {
        //  var_dump($model);exit;

        $html = '    <tr list_id=' . $this->model_to_id($model) . '>' .
            $this->echo_td_select($model);
        foreach ($this->Labels() as $key => $vo) {
            $html.= $this->html_val($key, $model);
        }
        $html.='</tr>';
        return $html;
    }

    /**
     * 显示每行的数据的各个字段
     */
    public function html_val($key, $model) {

        if ($key === 'control') {
            return $this->html_val_control($model);
        }

        return '<td class="' . $key . '" >' . $this->ModelTohtml($key, $model) . '</td>';
    }

    /**
     * 方便继承,多一层过滤
     */
    public function ModelTohtml($key, $model) {
        return $model->$key;
    }

    protected function toDel($isdel){
        if($isdel==0){
            return '正常';
        }else{
            return "删除";
        }
    }

    /**
     * 数据行的控制内容
     */
    public function html_val_control($model) {
        $data = $this->Labels();
        $html = '<th class="control">';
        if (isset($data['control'])) {
            foreach ($data['control'] as $vo) {
                $fun = 'val_control_' . $vo;
                if (method_exists($this, $fun)) {
                    $html.= $this->$fun($model);
                } else {
                    $html.="<span class='red'>请在{$this->className()}添加:public function {$fun}(\$model){}</span>";
                }
            }
        }
        $html.='</th>';
        return $html;
    }

    /**
     * 数据行的编辑
     */
    public function val_control_edit($model) {
        return Html::button('编辑', [
            'list_id' => $this->model_to_id($model),
            'class' => 'edit'
        ], Html::Colorinfo
        );
    }

    /**
     * 数据行的删除
     */
    public function val_control_delete($model) {
        return Html::button('删除', [
            'list_id' => $this->model_to_id($model),
            'class' => 'delete',
            'title' => $this->model_to_id($model)
        ], Html::Colordanger,Html::SizeXs
        );
    }

    /**
     * 主键的字段
     */
    public function get_primaryKey() {
        $pr = $this->get_model();
        $key = $pr->getKeyName();
        if (isset($key)) {
            return $key;
        } else {
            Fun::showmsg('获取primaryKey错误', Fun::ERROR_SHOW);
        }
    }

    /**
     * 返回表示model对象的唯一值
     */
    public function model_to_id($model) {
        $key = $this->get_primaryKey();
        return $model->$key;
    }

    /**
     * 顶部的标题的控制内容
     */
    public function top_control() {
        return Html::tag('th', '', ['class' => 'top_control', 'td_class' => 'control']);
    }

    /**
     * 显示默认的表格标题
     */
    public function Label_default($key) {
        if ($key === 'control') {
            return $this->top_control();
        }

        $lab = $this->Labels();


        $vo = $lab[$key];
        $arr = [];
        if ($vo === '' || is_array($vo)) {
            $arr = $vo;
        }else{
            $arr['width']=$vo;
        }
        if (empty($arr['html'])) {
            $keyarr = $this->get_model()->attributeLabels();
            if ($keyarr && isset($keyarr[$key]))
                $arr['html'] = $keyarr[$key];
            else {
                Fun::showmsg('没有在attributeLabels中找到' . $key);
            }
        }

        if (isset($arr['class'])) {
            $arr['class'].='  tab_title';
        } else {
            $arr['class'] = 'tab_title';
        }
        $arr['td_class'] = $key;



        return Html::tag('th', $arr['html'], $arr);
    }

    /**
     * 返回查询的条件
     */
    public function find() {
        $find = $this->get_model()->where([]);

        if (isset($_GET['submit']) && $_GET['submit'] == 'true') {
            $this->where($find);
        }

        $find->orderBy($this->get_primaryKey(),'DESC');
        return $find;
    }

    public function set_title($title) {
        $this->title = $title;
    }

    public function get_html_pages() {

         // echo($this->_get_data->links());exit;

        $appends=[];
        foreach ($this->getselectAttr() as $key=>$vo) {
            $appends[$key]=$_GET[$key]??'';
        }
        return  $this->_get_data->appends($appends)->links();
        //return LinkPager::widget(['pagination' => $this->pages]);
    }

    /**
     * 显示用于导出的命令行,命令
     */
    public function echoDcCommand() {

        $r = get_class($this);
        $r = base64_encode($r);
        // var_dump($r);exit;
        $yiiPath = Yii::$app->basePath;
        $uri = urldecode(
            parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
        );
        $uri.='?';
        foreach ($_GET as $key=>$val) {
            $uri.=$key.'='.$val.'&';
        }

        $uri.='download=true';
        $html = '<p><a style="
    color: #337AB7;
    font-size: 18px;
"   href="'.$uri.'">导出下载</a>,如果数据量太大系统无法响应,可以用下面的办法</p><p>在命令行中输入以下命令可以导出数据库,因为一般导出数据库需要很长的时间,所以需要放在命令行中执行</p>';

        $html.='<textarea readonly="readonly" class="command">'.$this->getphp().' ' . $yiiPath . '/yii dc ' . $r . '</textarea>';


        return $html;
    }

    /**
     * 获取php目录位置
     */
    private function getphp(){
        return '/usr/local/php/bin/php';
    }

    /**
     * 命令行被执行
     */
    public static function ComRun() {
        $class = self::className();
        $model = new $class;
        $model->showEcho = false;
        (new BaseExcelList())->load($model);
    }

    /**
     * 获取要现实的字段
     */
    public function ExceLabels() {
        $l = $this->Labels();
        $k = [];
        $keyarr = $this->get_model()->attributeLabels();
        foreach ($l as $key => $vo) {
            if ($key !== 'control') {
                if ($keyarr && isset($keyarr[$key]))
                    $k[$key] = $keyarr[$key];
                else {
                    echo '没有在attributeLabels中找到' . $key;
                    exit;
                }
            }
        }
        return $k;
    }

    /**
     * 数据中最大唯一值,用来动态检查数据更新
     */
    public function max_val() {
        $model = $this->find()->limit(1)->first();
        if ($model == null) {
            return '';
        }
        return $this->model_to_id($model);
    }

    /**
     * 获取当前数据的行数
     */
    public function count() {
        return $this->find()->count();
    }

    // public $layout = 'main';

    /**
     * 执行js发送过来的命令
     */
    public function run_api($type) {
        // var_dump($type);exit;
        if ($type === 'edit') {
            $this->js_html_on_edit(Yii::$app->request->post('list_id'));
        }
        if ($type === 'delete') {
            $this->js_on_delete(Yii::$app->request->post('list_id'));
        }
        if ($type === 'upfile') {
            $this->jsOnUpfile();
        }
        if ($type === 'dialog_ok') {////窗口中点击了确定
            $this->return_msg($this->dialog_ok());
        }
        if ($type === 'dialog_delete') {////点击了删除
            $this->return_msg($this->dialog_delete());
        }

        if ($type === 'start_jiankong') {
            $this->return_msg($this->on_start_jiankong());
        }
        if ($type === 'UpTrList') {
            $this->return_msg($this->on_UpTrList());
        }
    }

    /**
     * 获取表格数据
     */
    public function get_html($obj = null, $options = []) {
        if(Yii::$app->request->get('download')){
            $this->download();
            Yii::$app->end();
        }

        if (Yii::$app->request->post('BaseViewList')) {
            //print_r(Yii::$app->request->post());exit;
            $type = Yii::$app->request->post('type');
            $this->run_api($type);
            Yii::$app->end();
        }
        if ($this->IsBarMode()) {
            $this->baseBarChart = new BaseViewListBarChart($this);
            $dhtml = $this->baseBarChart->getHtml();
            if ($obj) {
                return $obj->renderContent($dhtml);
            } else {
                return $dhtml;
            }
        }
        $this->get_data();

        $html = $this->render('baseview', ['options' => $options]);
        return $html;
      /*  if (empty($obj)) {
            return $html;
        } else {
            echo $html;exit;
            return $obj->renderContent($html);
        }*/
    }

    /**
     * 返回数据给浏览器
     */
    public function return_msg($msg) {
        if ($msg === false) {
            echo json_encode(
                [
                    'content' => $this->errorMsg,
                    'error' => 1
                ]
            );
        } elseif ($msg === true) {
            echo json_encode(
                [
                    'content' => 'ok',
                    'error' => 0
                ]
            );
        } else {
            echo json_encode(
                [
                    'content' => $msg,
                    'error' => 0
                ]
            );
        }
    }

    /**
     * js 调用的添加窗口方法
     * $id如果为空,则是新增的
     */
    public function js_html_on_edit($id) {
        $model = $this->get_one_model($id);
        if ($model === false) {
            $this->echo_content(BaseViewList::TAG_ERROR, $this->msg);
        }
        ////var_dump($model);
        $this->echo_content(BaseViewList::TAG_OK, ['html' => $this->echo_dialog($model), 'id' => $id, 'r_id' => $this->c_rand()]);
    }

    public function echo_dialog($model) {
        return $this->render('echo_dialog', ['model' => $model]);
    }

    /**
     * 输出错误信息,并终止
     */
    private function echo_content($tag, $msg) {
        echo json_encode(['error' => $tag, 'content' => $msg]);
        Yii::$app->end();
    }

    /**
     * 返回该id的对象
     * $id如果为空,则是新增的
     *
     */
    public function get_one_model($id) {
        if ($id == '')
            return $this->get_model();
        else {
            $model = $this->get_model()->where([
                $this->get_primaryKey()=>$id
            ])->first();;

            if ($model === null) {
                $this->msg = '查找记录失败';
                return false;
            }
            return $model;
        }
    }

    private $msg = '';
    private $_get_data = null;

    /**
     * 获取当页的数据
     */
    public function get_data() {
        if ($this->_get_data !== null)
            return $this->_get_data;


        $query = $this->find(); //->where([]);


        $this->count = $query->count();
        return $this->_get_data=$query->paginate($this->PageSize);
        /*
        $this->pages = new Pagination(['totalCount' => $this->count, 'defaultPageSize' => $this->PageSize]);
        return $this->_get_data = $query->offset($this->pages->getOffset())
            ->limit($this->pages->getLimit())
            ->get();*/
    }

    /**
     * 在echo_dialog中需要显示的每一行的,如果是text类型
     */
    public function dialog_label_INTtext($vo, $model) {
        $zd = $vo['zd'];
        $val = 0;
        $modelArray = $this->get_model()->attributeLabels();
        $zd = $vo['zd'];
        //  var_dump($vo['zd']);exit;

        $title = isset($vo['title']) ? $vo['title'] : $modelArray[$vo['zd']];

        if (!empty($model->$zd)) {
            $val = $model->$zd;
        }
        $html = '<label class="bvl_label clearfix">
    <span class="bvl_title">' . $title . ':</span>
    <input xz="int"  zd="' . $vo['zd'] . '" type="text" id="bvl_' . $vo['zd'] . '" value="' . $val . '"/>
</label>';

        return $html;
    }



    /**
     * 在echo_dialog中需要显示的每一行的,如果是text类型
     */
    public function dialog_label_text($vo, $model) {
        $modelArray = $this->get_model()->attributeLabels();
        $zd = $vo['zd'];
      //  var_dump($vo['zd']);exit;

        $title = isset($vo['title']) ? $vo['title'] : $modelArray[$vo['zd']];
        $html = '<label class="bvl_label clearfix">
    <span class="bvl_title">' . $title. ':</span>
    <input  zd="' . $vo['zd'] . '" type="text" id="bvl_' . $vo['zd'] . '" value="' . Html::encode($model->$zd) . '"/>
</label>';

        return $html;
    }

    /**
     * 在echo_dialog中需要显示的每一行的,如果是text类型
     */
    public function dialog_label_textarea($vo, $model) {
        $modelArray = $this->get_model()->attributeLabels();
        $zd = $vo['zd'];
        $title = isset($vo['title']) ? $vo['title'] : $modelArray[$vo['zd']];
        $html = '<label class="bvl_label clearfix">
    <span class="bvl_title">' .$title . ':</span>
    <textarea  zd="' . $vo['zd'] . '" type="text" id="bvl_' . $vo['zd'] . '"  >' . Html::encode($model->$zd) . '</textarea>
</label>';

        return $html;
    }

    /**
     * 在echo_dialog中显示一个富文本编辑控件
     */
    public function dialog_label_texthtml($vo, $model) {
        $modelArray = $this->get_model()->attributeLabels();
        $zd = $vo['zd'];
        $title = isset($vo['title']) ? $vo['title'] : $modelArray[$vo['zd']];
        $html = '<label class="bvl_label clearfix">
    <span class="bvl_title">' . $title . ':</span>
    <textarea text="html" zd="' . $vo['zd'] . '" type="text" id="bvl_' . $vo['zd'] . '"  >' . $model->$zd . '</textarea>
</label>';

        return $html;
    }

    /**
     * 在echo_dialog中需要显示的每一行的,如果是list类型
     */
    public function dialog_label_list($vo, $model) {

        $modelArray = $this->get_model()->attributeLabels();
        $zd = $vo['zd'];
        $title = isset($vo['title']) ? $vo['title'] : $modelArray[$vo['zd']];
        $list = Html::activeDropDownList($model, $zd, $vo['data'], ['zd' => $vo['zd']]
        );

        $html = '<label class="bvl_label clearfix">
    <span class="bvl_title">' . $title . ':</span>
   ' . $list . '
</label>';
        return $html;
    }

    /**
     * 在echo_dialog中需要显示的每一行的,如果是img类型
     */
    public function dialog_label_img($vo, $model) {
        $zd = $vo['zd'];
        $modelArray = $this->get_model()->attributeLabels();
        $zd = $vo['zd'];
        $title = isset($vo['title']) ? $vo['title'] : $modelArray[$vo['zd']];

       /* $img = Html::img($model->$zd, ['class' => 'lable_img'
            ,
            'l_img' => $zd, 'onclick' => 'bvl.openImgUrl(this)'
        ]);*/
       $img='<img src="" class="lable_img" l_img="'.$zd.'" onclick="bvl.openImgUrl(this)" />';
        //    $img=  Html::a($img,$model->$zd,['target'=>'_blank','title'=>'查看原图']);
        //print_r($vo);exit;
        $html = '<label class="bvl_label clearfix label_img">
    <span class="bvl_title">' . $title. '</span>
   ' . $img . '
        <input class="input"  zd="' . $vo['zd'] . '" type="text" id="bvl_' . $vo['zd'] . '" value="' . $model->$zd . '"/>
            <button class="button_zd" img="' . $vo['zd'] . '"  value="上传">上传</button>
</label>';

        return $html;
    }

    public function render($view, $params = []) {

      //  var_dump($view, $params);exit;
      //  $params['context']=$this;
        $context=$this;
        $model=null;
        $topselect=null;
        if(isset($params['model'])){
            $model=$params['model'];
        }
        if(isset($params['topselect'])){
            $topselect=$params['topselect'];
        }
        $html = view('baseviewlist.'.$view,
            compact('context','model','topselect'))->render();
        return $html;
       // return parent::render('@app/components/baseviewlist/' . $view, $params);
    }

    private $_rand = null;

    /**
     * 获取一个随机字符串,一个对象只生成一个
     */
    public function c_rand() {
        if ($this->_rand === null) {
            $this->_rand = 'R_' . time() . '_' . rand(1, 1000);
        }
        return $this->_rand;
    }

    /**
     * js调用上传上传文件
     */
    public function jsOnUpfile() {
       $json= Upload::uploadImgByApi($this->Request,'imgFile',true);
       OA::Json(0,$json);
     //   (new baseviewlist\UpImgfile)->upimg();
    }

    /**
     * on_UpTrList
     * 更新一行数据
     */
    private function on_UpTrList() {
        $id = Yii::$app->request->post('list_id');
        $model = $this->get_one_model($id);
        return [
            'model' => $this->echo_tbody_tr($model),
            'list_id' => $this->model_to_id($model)
        ];
    }


    public $errorMsg='';

    /**
     * 在窗口中点击了确定按钮
     */
    private function dialog_ok() {
        $id = Yii::$app->request->post('bvl_id');
        $model = $this->get_one_model($id);
        $logArray = [];
        foreach ($this->dialog() as $vo) {
            if ($model[$vo['zd']] !== Yii::$app->request->post($vo['zd'])) {
                $logArray[$vo['zd']] = [
                    'old' => $model[$vo['zd']],
                    'new' => Yii::$app->request->post($vo['zd'])
                ];
                $model[$vo['zd']] = Yii::$app->request->post($vo['zd']);
            }
        }

        if (!$this->save_model($model)) {
            return false;
        }
        $isNewRecord=$model->isNewRecord;
        if ($r = $model->save()) {
            $re=$this->save_success($model,$isNewRecord);
          //  \app\models\Log::addLogBaseViewList($model,$logArray, $r,$isNewRecord,  $this->get_primaryKey().':'.$this->model_to_id($model));
            if($re===false){
                return false;
            }

            return [
                'model' => $this->echo_tbody_tr($model),
                'list_id' => $this->model_to_id($model)
            ];
        } else {
            /* \app\models\Error::set_error_array(
              $model->getErrors()
              ); */

        }

        return false;
    }

    /**
     * 方便重载,保存model时调用的,可能是新增也可能是保存,返回true表示允许保存
     */
    public function save_model($model) {
        return true;
    }

    /**
     * 保存成功后调用
     */
    public function save_success($model,$isNewRecord) {
        return true;
    }

    /**
     * 在窗口中点击了删除按钮
     */
    protected function dialog_delete() {
        $str_bvl_id = Yii::$app->request->post('bvl_id');
        $bvl_id = explode(',', $str_bvl_id);

        if ($this->delete_model($bvl_id) === false) {
            return false;
        }
        if ($this->get_model()->whereIn( $this->get_primaryKey(),  $bvl_id)->delete()) {
            return $str_bvl_id;
        } else {
            API::$errormsg= '删除失败';
            return false;
        }
    }

    /**
     * 方便重载,删除model  参数为id数组,如果允许删除,返回true,否则false
     */
    public function delete_model(&$ids) {
        return true;
    }

    /**
     * 是否启动自动监控,如果为0,在表示不启用自动检查,其它数字为间隔时间  毫秒
     */
    public function start_jiankong() {
        return $this->auto_detection * 1000;
    }

    /**
     * js端调用,获取js提供的最大值,然后获取更新的数据
     */
    public function on_start_jiankong() {

        return [
            'max_val' => $this->max_val(),
            'count' => $this->count(),
            'newhtml' => $this->get_new_data($_POST['max_val'])
        ];
    }

    /**
     * 方便重载,获取大于$maxid新的数据
     */
    public function get_new_data($maxId) {
        $model = $this->find()->andWhere($this->get_primaryKey() . '>:id', [':id' => $maxId])->limit($this->PageSize)->all();
        $html = [];
        foreach ($model as $vo) {
            $html[] = ['html' => $this->echo_tbody_tr($vo),
                'list_id' => $this->model_to_id($vo)
            ];
        }
        // var_dump($html);exit;
        return $html;
    }

    /**
     * 格式化时间
     */
    public function toTime($time) {
        if (empty($time)) {
            return '';
        }
        return Fun::date($time);
    }

    /**
     * 格式化为类型项目
     * $array  为一个数组
     * $var   数组中的key,
     * $defaulf  如果数组中的key不存在,则返回一个默认值
     */
    public function toType($array, $var, $defaulf = '') {
        if (isset($array[$var])) {
            return $array[$var];
        } else {
            return $defaulf;
        }
    }

    /**
     * 返回一个图片对象
     */
    public function toImg($src) {

        if (empty($src)) {
            $src ='/public/artdialog/skins/icons/question.png';
        }
        return '<img src="' . $src . '" class="toimg" />';

       /// return '<div class="toimg" style=" background-image: url(' . $src . ');"></div>';
    }

    /**
     * 根据表id,获取一个新的有数字和字母组成的数字
     */

    /**
     * 根据数值id返回字符串kid
     * ID的最大值是PHP_INT_MAX=2147483647
     *
     * $len表示生成的长度,如果不足这个长度则用0补充,如果为0,则不考虑长度
     * 默认为4位
     */
    public static function get_char($id, $char_len = 4) {
        $char = [ //'',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I',
            'J', 'K',
            'L',
            'M', 'N',
            'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
        ];
        //   $char=['0','1','2','3','4','5', '6', '7', '8',];

        $len = count($char);
        $id = (INT) $id;
        if ($id === 0) {
            return $char[0];
        }
        $str = '';
        for (; $id != 0;) {
            $str = $char[$id % $len] . $str; //;echo ' ';
            $id = (INT) ($id / $len);
        }
        if ($char_len === 0) {
            return $str;
        }
        $char_xc = $char_len - strlen($str);
        if ($char_xc <= 0) {
            return $str;
        }
        return str_pad($str, $char_len, $char[0], STR_PAD_LEFT);
    }

    /**
     * 顶部的选择区,参数,如果为空,则不显示选择器
     */
    public function getselectAttr() {


        /*
          $where = [
            'word' =>
                [
                    'title' => '名字和注释',
                    'inputtype' => self::htmlText,
                ],
            'api' =>
                [
                    'title' => '接口字符串和类名',
                    'inputtype' => self::htmlText,
                ],
            'auth' =>
                [
                    'title' => '授权',
                    'inputtype' => self::dropDownList,
                    'items' => ['' => '所有'] + ApilistModel::getAuthArray(),
                    'default' => ''
                ],
            'isrun' =>
                [
                    'title' => '是否启用',
                    'inputtype' => self::dropDownList,
                    'items' => ['' => '所有', 1 => '启用',
                        0 => '关闭'],
                    'default' => ''
                ]
        ];


        */
        return [];
    }

    /**
     * 根据选择器的搜索,设置条件
     */
    public function andWhere($find) {
        //  $find->andWhere();
        $attr = $this->getselectAttr();
        foreach ($attr as $key => $vo) {
            if (isset($vo['where']))
                $find->andWhere($vo['where']);
        }
        // print_r($attr);  exit;
    }

    /**
     * 表格上面的内容
     */
    public function tophtml() {
        return '';
    }

    /**
     * 顶部的选择区
     */
    public function topSelect() {
        $html = $this->tophtml();
        if ($this->getselectAttr() === []) {
            return $html;
        }

        return $html . $this->render('topselect');
    }

    /**
     * 文本框
     */
    const htmlText = 1;

    /**
     * 下拉框
     */
    const dropDownList = 2;

    /**
     * 返回一个输入框
     * $type表示类型,如果是htmlText则表示为文本类型
     */
    public static function htmlinput($type = self::htmlText, $val = '', $name = '', $list = []) {
        if ($type === self::htmlText) {
            return Html::input('text', $name, $val);
        }


        if ($type === self::dropDownList) {
            return Html::dropDownList($name, $val, $list);
        }
        return '';
    }


    /**
     * 判断是否启用
     */
    public $BarChart = false;

    /**
     * 条形表对象
     */
    public $baseBarChart;

    /**
     * 判断是否为条形模式
     */
    public function IsBarMode() {
        if ($this->BarChart === false) {
            return false;
        }
        if (isset($_GET['barmode']) && $_GET['barmode'] === 'true') {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 将数组转换为字符
     */
    public function ArrayToTitle($val, $array)
    {
        return isset($array[$val]) ? $array[$val] : $val;
    }
}